#!/usr/bin/env node

import fetch from 'node-fetch';

const SERVER_URL = 'http://localhost:3000';

async function testNewAPI() {
    console.log('🧪 Testing New API Design...\n');
    
    // 1. Initialize session
    console.log('1️⃣ Initializing session...');
    let sessionId;
    try {
        const initRes = await fetch(`${SERVER_URL}/mcp`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                jsonrpc: '2.0',
                id: 'init',
                method: 'initialize',
                params: { protocolVersion: '2025-03-26' }
            })
        });
        const initData = await initRes.json();
        sessionId = initData.result?.sessionId;
        console.log('✅ Session initialized:', sessionId);
    } catch (error) {
        console.error('❌ Failed:', error.message);
        return;
    }
    
    // 2. Test legacy API with simple name (should get warning)
    console.log('\n2️⃣ Testing legacy API with simple class name...');
    try {
        const res = await fetch(`${SERVER_URL}/mcp`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Mcp-Session-Id': sessionId
            },
            body: JSON.stringify({
                jsonrpc: '2.0',
                id: 'legacy-test',
                method: 'tools/call',
                params: {
                    name: 'find_class_in_local_repository',
                    arguments: { className: 'AuditDomain' }
                }
            })
        });
        const data = await res.json();
        const result = JSON.parse(data.result?.content?.[0]?.text || '{}');
        if (result.warning) {
            console.log('✅ Got expected warning:', result.warning);
        } else {
            console.log('⚠️  Unexpected response:', result);
        }
    } catch (error) {
        console.error('❌ Failed:', error);
    }
    
    // 3. Search for classes
    console.log('\n3️⃣ Searching for classes with keyword "AuditDomain"...');
    let foundClasses = [];
    try {
        const res = await fetch(`${SERVER_URL}/mcp`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Mcp-Session-Id': sessionId
            },
            body: JSON.stringify({
                jsonrpc: '2.0',
                id: 'search',
                method: 'tools/call',
                params: {
                    name: 'search_classes',
                    arguments: { 
                        keyword: 'AuditDomain',
                        limit: 10
                    }
                }
            })
        });
        const data = await res.json();
        const result = JSON.parse(data.result?.content?.[0]?.text || '{}');
        
        console.log(`✅ Found ${result.totalFound} classes, returned ${result.returned}`);
        if (result.results && result.results.length > 0) {
            foundClasses = result.results;
            console.log('   First 3 results:');
            result.results.slice(0, 3).forEach(cls => {
                console.log(`   - ${cls.fullName}`);
                console.log(`     JAR: ${cls.artifact.jarPath}`);
            });
        }
    } catch (error) {
        console.error('❌ Failed:', error);
    }
    
    // 4. Decompile a specific class
    if (foundClasses.length > 0) {
        const targetClass = foundClasses[0];
        console.log(`\n4️⃣ Decompiling class: ${targetClass.fullName}...`);
        
        try {
            const res = await fetch(`${SERVER_URL}/mcp`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Mcp-Session-Id': sessionId
                },
                body: JSON.stringify({
                    jsonrpc: '2.0',
                    id: 'decompile',
                    method: 'tools/call',
                    params: {
                        name: 'decompile_class',
                        arguments: { 
                            fullClassName: targetClass.fullName,
                            jarPath: targetClass.artifact.jarPath
                        }
                    }
                })
            });
            const data = await res.json();
            const result = JSON.parse(data.result?.content?.[0]?.text || '{}');
            
            if (result.success) {
                console.log('✅ Decompilation successful!');
                console.log(`   Source length: ${result.source?.length || 0} characters`);
                
                // Show first few lines of source
                if (result.source) {
                    const lines = result.source.split('\n').slice(0, 5);
                    console.log('   First 5 lines:');
                    lines.forEach(line => console.log(`     ${line}`));
                }
            } else {
                console.log('❌ Decompilation failed:', result.error);
            }
        } catch (error) {
            console.error('❌ Failed:', error);
        }
    }
    
    // 5. Test decompile with non-existent class
    console.log('\n5️⃣ Testing decompile with non-existent class...');
    try {
        const res = await fetch(`${SERVER_URL}/mcp`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Mcp-Session-Id': sessionId
            },
            body: JSON.stringify({
                jsonrpc: '2.0',
                id: 'decompile-404',
                method: 'tools/call',
                params: {
                    name: 'decompile_class',
                    arguments: { 
                        fullClassName: 'com.nonexistent.NoSuchClass'
                    }
                }
            })
        });
        const data = await res.json();
        const result = JSON.parse(data.result?.content?.[0]?.text || '{}');
        
        if (result.error && result.error.includes('not found')) {
            console.log('✅ Got expected error:', result.error);
        } else {
            console.log('⚠️  Unexpected response:', result);
        }
    } catch (error) {
        console.error('❌ Failed:', error);
    }
    
    console.log('\n✨ Test completed!');
    process.exit(0);
}

testNewAPI().catch(console.error);